<template>
  <div id="user-manager-container">
    <a-button type="primary" @click="addUserVisible = true">
      <UserAddOutlined />
      添加管理员
    </a-button>
    <UserTable :users="users" @delete="deleteUser" @permission="changePermission" />
    <AddAdmin :visible="addUserVisible"
              @close="addUserVisible = false"
              @ok="addUserVisible = false;getUsers();" />
    <EditPermission :user="currentUser"
                    :visible="editPermissionVisible"
                    @ok="editPermissionOk"
                    @cancel="editPermissionVisible = false" />
  </div>
</template>

<script setup>
import {UserAddOutlined} from "@ant-design/icons-vue";
import {onMounted, ref} from "vue";
import {apiDelete, apiGet} from "../../../fentch";
import {message, notification} from "ant-design-vue";
import AddAdmin from "../../../components/admin/user/AddAdmin.vue";
import UserTable from "../../../components/admin/user/UserTable.vue";
import EditPermission from "../../../components/admin/user/EditPermission.vue";

/**
 * 基础数据
 */
const users = ref([])
const addUserVisible = ref(false)
// 用于编辑权限与禁用账户的临时数据
const currentUser = ref({})
const editPermissionVisible = ref(false)
const changePermission = user => {
  currentUser.value = user;
  editPermissionVisible.value = true
}
const editPermissionOk = () => {
  editPermissionVisible.value = false
  getUsers()
}

/**
 * 获取用户
 */
const getUsers = () => {
  apiGet('/users').then(res => {
    const data = res.data.data;
    if (res.data.code === 0) {
      users.value = data.data
      return
    }
    notification.error({
      description: '错误',
      message: res.data.message
    })
  })
}

/**
 * 删除用户
 */
const deleteUser = id => {
  apiDelete(`/users/${id}`).then(res => {
    if (res.data.code === 0) {
      getUsers()
      return
    }
    message.error(res.data.message)
  })
}

onMounted(() => {
  getUsers()
})
</script>

<style scoped>
.user-table {
  margin-top: 20px;
}
</style>